package com.kakavr.user.service;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.kakavr.base.exception.ValidateParamException;
import com.kakavr.base.service.BaseService;
import com.kakavr.page.Pagination;
import com.kakavr.page.constant.PaginationConstant;
import com.kakavr.result.constant.MsgConstants;
import com.kakavr.shop.service.ITradeFlowService;
import com.kakavr.user.dao.IUserDao;
import com.kakavr.util.DateTimeUtils;

@Service
public class UserService extends BaseService implements IUserService {
	@Resource
	private IUserDao userDao;
	
	@Resource
	private ITradeFlowService tradeFlowService;

	@Override
	public Map<String, Object> getUserInfo(Map<String, Object> map) {
		return userDao.getUserInfo(map);
	}

	@Override
	public void addUser(Map<String, Object> map) {
		map.put("createtime", new Date());
		if(null == map.get("isActivity")){
			map.put("isActivity", 0);
		}
		if(null==map.get("times")){
			map.put("times", 0);//赋予初始值
		}
		userDao.addUser(map);
	}

	@Override
	public void updateUser(Map<String, Object> map) {
		userDao.updateUser(map);
	}
	
	
	@Override
	public Map<String, Object> getUserBywxid(Map<String, Object> map) {
		return userDao.getUserBywxid(map);
	}

	
	@Override
	public void addUserByRegister(Map<String, Object> map) {
		Map<String, Object> user = this.getUserInfo(map);
		if(null == user || user.isEmpty()){
			if(null==map.get("times")){
				map.put("times", 0);
			}
			map.put("createtime", new Date());
			userDao.addUser(map);
			Map<String,Object> userinfo=userDao.getUserInfo(map);
			if(StringUtils.isNotBlank(String.valueOf(map.get("times")))&&StringUtils.isNotBlank(String.valueOf(map.get("money")))){
				map.put("userId", userinfo.get("id"));
				tradeFlowService.addActivityTradeFlow(map);//保存活动赠送的记录
			}
		}else{
			throw new ValidateParamException(MsgConstants.MSG_CODE_1003,
					MsgConstants.MSG_CONTENT_1003, "用户名");
		}
	}

	@Override
	public void addUserLogin(Map<String, Object> map) {
		userDao.addUserLogin(map);
	}

	@Override
	public Map<String, Object> selectUserLogin(Map<String, Object> map) {
		return userDao.selectUserLogin(map);
	}

	@Override
	public Pagination<Map<String, Object>> selectUserList(
			Map<String, Object> map) {
		PageHelper.startPage(NumberUtils.toInt((String) map
				.get(PaginationConstant.PAGE_NO_NAME)), NumberUtils
				.toInt((String) map.get(PaginationConstant.PAGE_SIZE_NAME)));
		return new Pagination<Map<String,Object>>(userDao.selectUserList(map));
	}
	
	@Override
	public Map<String,Object> selectCountNum(Map<String,Object> map){
		return userDao.selectCountNum(map);
	}

}
